package com.weim.weim.util;

import lombok.extern.slf4j.Slf4j;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.*;
import java.util.Base64;

/**
 * @program: qianfan
 *
 * @description:
 *
 * @author: ju
 *
 * @create: 2024-07-08 15:38
 **/
@Slf4j
@Component
@Configuration
public class VideoFrameCapture {

  /*  public static void main(String[] args) throws IOException {
        String inputFilename = "/Users/u0043780/Downloads/e2081b642adbc304ac291379e60a7b.mp4";
        FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(inputFilename);
        grabber.start();



        int totalFrames = (int) (grabber.getLengthInFrames() + 0.5);
        for (int i = 0; i < totalFrames; i++) {
            Frame frame = grabber.grabFrame();
            if (frame != null) {
                // 这里可以处理每一帧，比如保存为图片
                if (i % 100 == 0) { // 例如，每100帧保存一次
                    String outputFilename = "frame-" + i + ".png";
                    Frame convertedFrame = Frame.cloneWithSize(frame, 640, 480);
                    Java2DFrameConverter converter = new Java2DFrameConverter();
                    BufferedImage image = converter.convert(convertedFrame);
                    ImageIO.write(image, "PNG", new File(outputFilename));
                }
                frame.close();
            }
        }

        grabber.stop();
    }*/



    public  String getVideoPicture(MultipartFile multipartFile) throws Exception{

        File videoFile = multipartFileToFileInMemory(multipartFile, "/Users/u0043780/Downloads");
        String imgPath = "/Users/u0043780/Downloads";
        if (videoFile.exists()) {
            System.out.println("视频存在");
            //实例化“截取视频首帧”对象
            FFmpegFrameGrabber ff = new FFmpegFrameGrabber(videoFile);
            ff.start();
            int width = ff.getImageWidth();
            int height = ff.getImageHeight();
            System.out.println("宽：" + width + "；高：" + height);

            long ftp = ff.getLengthInFrames();
            System.out.println("一共有：" + ftp + "帧");
            // 视频帧率
            double videoFrameRate = ff.getVideoFrameRate();
            System.out.println("帧率：" + videoFrameRate);
            long delayedTime = ff.getLengthInTime() / 1000000;
            System.out.println("秒数：" + delayedTime);
            int step = 10;
            System.out.println("每隔：" + step + "帧取一帧");
            long count = ftp / step;
            for(long i = 0; i < count; i++){
                System.out.println("截图进度：" + i + "/" +count);
//                long time = (step * (i + 1)) * 1000000L;
//                ff.setTimestamp(time);
                ff.setFrameNumber((int) (step * i + 1));
                Frame f = ff.grabImage();
                //生成文件名称
                String fileName = imgPath + "/" + i + ".jpeg";
                System.out.println("截图保存：" +fileName);
                File out = new File(fileName);
                ImageIO.write(frameToBufferedImageNew(f), "jpeg", out);


                String imgBase64 = frameToBufferedImage(f);
                return imgBase64;
            }
            ff.close();
            ff.stop();
        } else {

        }
        return null;
    }

    private static RenderedImage frameToBufferedImageNew(Frame frame) {
        //创建BufferedImage对象
        Java2DFrameConverter converter = new Java2DFrameConverter();
        BufferedImage bufferedImage = converter.getBufferedImage(frame);
        return bufferedImage;
    }

    private  String frameToBufferedImage(Frame frame) {
        //创建BufferedImage对象
        Java2DFrameConverter converter = new Java2DFrameConverter();
        BufferedImage bufferedImage = converter.getBufferedImage(frame);
        String imageToBase64 = imageToBase64(bufferedImage, "jpeg");
        String s = encodeImageToBase64Binary("/Users/u0043780/Downloads/0.jpeg");
        System.out.println(s.equals(imageToBase64));
        return imageToBase64;
    }

    public  String encodeImageToBase64Binary(String imagePath) {

        try{

            // 假设你的图片文件路径是"path/to/your/image.jpg"
            File imageFile = new File(imagePath);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            // 读取图片文件到字节输出流中
            byte[] buffer = new byte[4096];
            int bytesRead;
            try (FileInputStream fis = new FileInputStream(imageFile)) {
                while ((bytesRead = fis.read(buffer)) != -1) {
                    baos.write(buffer, 0, bytesRead);
                }
            }

            // 使用Base64对字节数组进行编码
            byte[] bytes = baos.toByteArray();
            return Base64.getEncoder().encodeToString(bytes);
        }catch (Exception e){

        }
        return null;
    }

    public static String imageToBase64(BufferedImage image, String formatName) {
        String base64Image = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            // 将BufferedImage编码为指定格式的字节数据，并写入到ByteArrayOutputStream中
            ImageIO.write(image, formatName, baos);

            // 将ByteArrayOutputStream中的字节数据转换为Base64编码的字符串
            byte[] imageBytes = baos.toByteArray();
            base64Image = Base64.getEncoder().encodeToString(imageBytes);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return base64Image;
    }

    public static void main(String[] args) {
        try {
            String videoPath = "/Users/u0043780/Downloads/1227_1709624377.mp4";
            String imgPath = "/Users/u0043780/Downloads";
            //getVideoPicture(videoPath, imgPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public File multipartFileToFileInMemory(MultipartFile multipartFile, String tempDir) throws IOException {
        File tempFile = File.createTempFile("tempFile", ".tmp", new File(tempDir));
        tempFile.deleteOnExit(); // JVM退出时自动删除文件  
        try (FileOutputStream fos = new FileOutputStream(tempFile)) {
            fos.write(multipartFile.getBytes());
        }
        return tempFile;
    }



}
